<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cloud Terminal</title>
    <link rel="icon" href="image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><rect width=%22100%22 height=%22100%22 fill=%22%233b82f6%22/><path d=%22M20 40h60M20 60h60M20 50h20M50 50h30%22 stroke=%22white%22 stroke-width=%226%22 stroke-linecap=%22round%22/></svg>">
    <script src="https://cdn.jsdelivr.net/npm/xterm@5.3.0/lib/xterm.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit@0.8.0/lib/xterm-addon-fit.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css" />
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Google Sans', 'Segoe UI', system-ui, -apple-system, sans-serif;
            background: linear-gradient(135deg, #1a237e 0%, #283593 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .terminal-container {
            width: 100%;
            max-width: 1200px;
            height: 80vh;
            background: #0d1117;
            border-radius: 16px;
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .terminal-header {
            background: linear-gradient(90deg, #1e293b 0%, #334155 100%);
            padding: 16px 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #334155;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .terminal-title {
            color: #f1f5f9;
            font-size: 16px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .terminal-actions {
            display: flex;
            gap: 12px;
        }

        .action-btn {
            width: 28px;
            height: 28px;
            border-radius: 6px;
            background: #334155;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #cbd5e1;
            transition: all 0.2s ease;
        }

        .action-btn:hover {
            background: #475569;
            color: #f1f5f9;
        }

        .action-btn.minimize { background: #64748b; }
        .action-btn.maximize { background: #64748b; }
        .action-btn.close { 
            background: #ef4444; 
            color: white;
        }
        .action-btn.close:hover { 
            background: #dc2626; 
        }

        .terminal-body {
            flex: 1;
            padding: 20px;
            background: #0d1117;
        }

        #terminal {
            width: 100%;
            height: 100%;
            border-radius: 8px;
            overflow: hidden;
        }

        .connection-status {
            position: absolute;
            bottom: 20px;
            right: 20px;
            background: rgba(0, 0, 0, 0.7);
            color: #10b981;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(16, 185, 129, 0.3);
        }

        .terminal-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(13, 17, 23, 0.95);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 10;
            color: white;
        }

        .overlay-content {
            text-align: center;
            max-width: 600px;
            padding: 40px;
        }

        .overlay-content h2 {
            font-size: 28px;
            margin-bottom: 16px;
            color: #60a5fa;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
        }

        .overlay-icon {
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
            font-weight: bold;
        }

        .overlay-content p {
            color: #cbd5e1;
            line-height: 1.6;
            margin-bottom: 24px;
        }

        .connect-btn {
            background: linear-gradient(90deg, #3b82f6 0%, #60a5fa 100%);
            color: white;
            border: none;
            padding: 12px 32px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .connect-btn:hover {
            transform: translateY(-2px);
        }

        .terminal-header-icon {
            width: 20px;
            height: 20px;
            background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%);
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            color: white;
        }

        .reconnect-btn {
            background: linear-gradient(90deg, #ef4444 0%, #f87171 100%);
            margin-top: 16px;
        }

        body.fullscreen {
            padding: 0;
            background: #0d1117;
        }

        body.fullscreen .terminal-container {
            max-width: none;
            height: 100vh;
            border-radius: 0;
            box-shadow: none;
        }
    </style>
</head>
<body>
    <div class="terminal-container">
        <div class="terminal-header">
            <div class="header-left">
                <div class="terminal-header-icon">C</div>
                <div class="terminal-title">
                    Cloud Shell
                </div>
            </div>
            <div class="terminal-actions">
                <button class="action-btn minimize" title="Minimize">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M4 12h16v2H4z"/>
                    </svg>
                </button>
                <button class="action-btn maximize" title="Maximize" id="maximizeBtn">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M4 4h16v16H4z"/>
                    </svg>
                </button>
                <button class="action-btn close" title="Close">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                    </svg>
                </button>
            </div>
        </div>
        <div class="terminal-body">
            <div id="terminal"></div>
        </div>
        <div class="connection-status">Connected • us-central1</div>
        
        <div class="terminal-overlay" id="connectionOverlay">
            <div class="overlay-content">
                <h2>
                    <div class="overlay-icon">C</div>
                    Cloud Shell Terminal
                </h2>
                <p>Connecting to your Google Cloud environment. This terminal provides real-time access to your backend shell session via WebSocket.</p>
                <div id="connectionMessage">Connecting to WebSocket server...</div>
                <button class="connect-btn" id="connectBtn" style="display: none;">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="white">
                        <path d="M3.5 18.995l.5-.005v-6l-2 2-.707-.707 3-3 3 3-.707.707-2-2v6h-1zm17 0v-6l-2 2-.707-.707 3-3 3 3-.707.707-2-2v6h-1zM12 21l-6-6h2.917l1.28 1.281 1.722 1.722.081.081 1.722-1.722 1.28-1.281h2.917l-6 6z"/>
                    </svg>
                    Reconnect
                </button>
            </div>
        </div>
    </div>

    <script>
        // Initialize terminal
        const term = new Terminal({
            fontFamily: 'Menlo, Monaco, "Courier New", monospace',
            fontSize: 14,
            lineHeight: 1.2,
            cursorBlink: true,
            cursorStyle: 'block',
            theme: {
                background: '#0d1117',
                foreground: '#e6edf3',
                cursor: '#60a5fa',
                selection: 'rgba(96, 165, 250, 0.3)',
                black: '#0d1117',
                red: '#f85149',
                green: '#3fb950',
                yellow: '#d29922',
                blue: '#58a6ff',
                magenta: '#bc8cff',
                cyan: '#76e3ea',
                white: '#e6edf3',
                brightBlack: '#6e7681',
                brightRed: '#ffa198',
                brightGreen: '#56d364',
                brightYellow: '#e3b341',
                brightBlue: '#79c0ff',
                brightMagenta: '#d2a8ff',
                brightCyan: '#76e3ea',
                brightWhite: '#ffffff'
            }
        });

        const fitAddon = new FitAddon.FitAddon();
        term.loadAddon(fitAddon);
        term.open(document.getElementById('terminal'));

        // DOM elements
        const connectionOverlay = document.getElementById('connectionOverlay');
        const connectionMessage = document.getElementById('connectionMessage');
        const connectBtn = document.getElementById('connectBtn');
        const maximizeBtn = document.getElementById('maximizeBtn');
        const body = document.body;

        // Auto-detect WebSocket URL based on current page
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const WS_URL = `${protocol}//${window.location.host}`;

        // Fullscreen functionality
        let isFullscreen = false;

        function toggleFullscreen() {
            if (!isFullscreen) {
                body.classList.add('fullscreen');
                maximizeBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M8 8h8v8H8z"/></svg>';
                maximizeBtn.title = 'Restore';
                isFullscreen = true;
            } else {
                body.classList.remove('fullscreen');
                maximizeBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M4 4h16v16H4z"/></svg>';
                maximizeBtn.title = 'Maximize';
                isFullscreen = false;
            }
            // Resize terminal after fullscreen toggle
            setTimeout(() => {
                resizeTerminal();
            }, 100);
        }

        maximizeBtn.addEventListener('click', toggleFullscreen);

        // Resize terminal function with size synchronization
        function resizeTerminal() {
            try {
                fitAddon.fit();
                
                // Ensure minimum size for better vim experience
                const cols = Math.max(term.cols, 80);
                const rows = Math.max(term.rows, 24);
                
                if (term.cols !== cols || term.rows !== rows) {
                    term.resize(cols, rows);
                }
                
                // Send resize event to backend
                sendResizeEvent();
            } catch (error) {
                console.warn('Resize failed:', error);
            }
        }

        // Send resize event to backend
        function sendResizeEvent() {
            if (socket && socket.readyState === WebSocket.OPEN) {
                const resizeMessage = {
                    type: 'resize',
                    cols: term.cols,
                    rows: term.rows
                };
                socket.send(JSON.stringify(resizeMessage));
            }
        }

        // Handle window resize with debounce
        let resizeTimeout;
        window.addEventListener('resize', () => {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(() => {
                resizeTerminal();
            }, 250);
        });

        // WebSocket connection
        let socket = null;

        function connectWebSocket() {
            connectionOverlay.style.display = 'flex';
            connectionMessage.textContent = 'Connecting to WebSocket server...';
            connectBtn.style.display = 'none';

            socket = new WebSocket(WS_URL);

            socket.onopen = () => {
                console.log('WebSocket connected to:', WS_URL);
                connectionOverlay.style.display = 'none';
                term.focus();
                
                // Send initial resize after connection
                setTimeout(() => {
                    resizeTerminal();
                }, 100);
            };

            socket.onmessage = (event) => {
                // Handle binary data (ArrayBuffer) and text data
                if (event.data instanceof ArrayBuffer) {
                    const decoder = new TextDecoder('utf-8');
                    const text = decoder.decode(event.data);
                    term.write(text);
                } else {
                    term.write(event.data);
                }
            };

            socket.onclose = (event) => {
                console.log('WebSocket disconnected', event);
                if (event.wasClean) {
                    connectionMessage.textContent = 'Connection closed cleanly.';
                } else {
                    connectionMessage.textContent = 'Connection lost. Attempting to reconnect...';
                    connectBtn.style.display = 'inline-block';
                    connectBtn.textContent = 'Reconnect';
                    connectBtn.className = 'connect-btn reconnect-btn';
                }
                connectionOverlay.style.display = 'flex';
                term.write('\r\n\x1b[31mConnection closed.\x1b[0m\r\n');
            };

            socket.onerror = (error) => {
                console.error('WebSocket error:', error);
                connectionMessage.textContent = 'Connection failed. Please check if the server is running.';
                connectBtn.style.display = 'inline-block';
                connectBtn.textContent = 'Retry Connection';
                connectBtn.className = 'connect-btn';
            };
        }

        // Handle terminal input
        term.onData((data) => {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.send(data);
            }
        });

        // Reconnect button
        connectBtn.addEventListener('click', () => {
            connectWebSocket();
        });

        // Close button functionality
        document.querySelector('.action-btn.close').addEventListener('click', () => {
            if (socket) {
                socket.close();
            }
            connectionOverlay.style.display = 'flex';
            term.reset();
        });

        // Initialize terminal size and connection
        window.addEventListener('load', () => {
            resizeTerminal();
            connectWebSocket();
        });

        // Handle page visibility changes to maintain connection
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden && socket && socket.readyState !== WebSocket.OPEN) {
                connectWebSocket();
            }
        });
    </script>
</body>
</html>
